//
//  ByDocumentaryVC.m
//  caipiao_ios
//
//  Created by mc on 2018/7/3.
//  Copyright © 2018年 ZhangZhanbin. All rights reserved.
//

#import "ByDocumentaryVC.h"
#import "ByDocumentaryHeadView.h"
#import "ByDocumentarySectionView.h"
#import "ByCoreViewSegmentControl.h"
#import "ByDocumentaryTitleCell.h"
#import "ByDocumentaryOtherCell.h"
#import "ByDocumentaryListVC.h"
#import "ByDocumentRedsCell.h"
#import "ByDocumentCell.h"
#import "ByDocumentaryUserVC.h"
#import "ByDocumentaryDetailVC.h"
#import "ByDocumentaryCreateVC.h"
#import "ByDocumentaryBombView.h"


@interface ByDocumentaryVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) ByCoreViewSegmentControl *segTitle;

@property (nonatomic, strong) NSMutableArray *redArray;

@property (nonatomic, assign) NSInteger type;
@property (nonatomic, assign) NSInteger bigType;

@property (nonatomic, strong) NSMutableArray *dataArray;


@property (nonatomic, strong) ByDocumentaryBombView *handleBombView;

@property (nonatomic, strong) ByNetModel *netModel;

@property (nonatomic, strong) ByPayBombView *payBombView;

@property (nonatomic, strong) ByNetModel *orderModel;

@end

@implementation ByDocumentaryVC


- (ByPayBombView *)payBombView{
    if (_payBombView == nil) {
        _payBombView = [[ByPayBombView alloc] init];
        
        __weak typeof(self) weakSelf = self;
        _payBombView.sureBlock = ^(){
            [weakSelf.payBombView remove];
            weakSelf.payBombView = nil;
        };
        
        _payBombView.otherSureBlock = ^(NSString *str,NSInteger type){
            
            [weakSelf.payBombView remove];
            weakSelf.payBombView = nil;
            
            if (type == 1) {
                ByWebViewController *vc = [[ByWebViewController alloc] initWithTotalUrlString:str];
                vc.titleString = @"支付宝支付";
                [weakSelf by_normalPush:vc hasNavi:YES];
            }else{
                ByWechatPayQrView *vc = [[ByWechatPayQrView alloc] init];
                vc.title = @"微信支付";
                vc.str = str;
                [weakSelf by_normalPush:vc hasNavi:YES];
            }
            
        };
        
        _payBombView.selectBlock = ^(NSInteger index){

        };
    }
    return _payBombView;
}


- (ByDocumentaryBombView *)handleBombView{
    if (_handleBombView == nil) {
        _handleBombView = [[ByDocumentaryBombView alloc] init];
        
        __weak typeof(self) weakSelf = self;
        __weak typeof(ByDocumentaryBombView *) weakSelfView = _handleBombView;
        _handleBombView.updateBlock = ^(){
            weakSelfView.totalLabel.text = [NSString stringWithFormat:@"共%ld元",self.netModel.single_amount.integerValue * weakSelfView.addMinusView.countLabel.text.integerValue];
        };
        _handleBombView.moneyLabel.text = [NSString stringWithFormat:@"最低跟单金额:%@元",weakSelf.netModel.low_amount];
        _handleBombView.totalLabel.text = [NSString stringWithFormat:@"共%ld元",weakSelf.netModel.single_amount.integerValue * 5];
        
        _handleBombView.betBlock = ^(){
            if (weakSelf.netModel.low_amount.integerValue > weakSelf.netModel.single_amount.integerValue * weakSelfView.addMinusView.countLabel.text.integerValue) {
                [ByCoreToolAlert showOnlyText:@"跟单金额小于最低跟单金额"];
                [weakSelf.handleBombView remove];
                weakSelf.handleBombView = nil;
                return;
                
            }
            [ByCoreToolAlert showLoadind:@"处理中" hasMasker:YES];
            ByNetModel *netModel = [[ByNetModel alloc] init];
            netModel.plan_id = weakSelf.netModel.ID;
            netModel.num = weakSelfView.addMinusView.countLabel.text;
            [ByDocumentaryApi followOrderFollowPlan:netModel success:^(ByNetBaseResult *result) {
                [ByCoreToolAlert hideHud];
                [weakSelf.handleBombView remove];
                weakSelf.handleBombView = nil;
                
                weakSelf.orderModel = [[ByNetModel alloc] initContentWithDic:result.data[@"data"]];
                weakSelf.payBombView.moneyLabel.text = [NSString stringWithFormat:@"%@元", weakSelf.orderModel.amount];
                weakSelf.orderModel = weakSelf.orderModel;
                [weakSelf.payBombView show];
                
            } failure:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showFailureWithText:result.msg];
                [weakSelf.handleBombView remove];
                weakSelf.handleBombView = nil;
            }];
            
        };
    }
    return _handleBombView;
}


- (NSMutableArray *)redArray{
    if (_redArray == nil) {
        _redArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _redArray;
}


- (NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"跟单";
    self.type = 1;
    self.bigType = 0;
    [self initViews];
    
    [self loadData];
    
    ByCoreRefreshGifHeader *header = [ByCoreRefreshGifHeader headerWithRefreshingBlock:^{
        [self loadData];
    }];
    self.tableView.mj_header = header;
}


- (void)loadData{
    
    if (!BY_USER) {
        [self.tableView.mj_header endRefreshing];
        return;
    }
    ByNetModel *netModel = [[ByNetModel alloc] init];
    netModel.type = self.type;
    if (self.bigType == 1) {
        netModel.is_follow = @"1";
    }else{
        netModel.is_follow = @"0";
    }
    
    NSLog(@"is_follow = %@", netModel.is_follow);
    [ByCoreToolAlert showLoadind:@"加载中" hasMasker:YES];
    [ByDocumentaryApi followOrderIndex:netModel  success:^(ByNetBaseResult *result) {
        [self.tableView.mj_header endRefreshing];
        [ByCoreToolAlert hideHud];
        NSDictionary *dictionary = result.data[@"data"];
        [self.dataArray removeAllObjects];
        for (NSDictionary *dic in dictionary[@"list"]) {
            ByNetModel *netModel = [[ByNetModel alloc] initContentWithDic:dic];
            
            if (netModel.origin_num.length > 0) {
                if (netModel.lottery_type.integerValue == 1) {
                    netModel.planDic = [ByFootBallHandle getFootBallGameResultWithPlan:netModel.origin_num];
                }else{
                    netModel.planDic = [ByBasketBallHandle getBasketBallGameResultWithPlan:netModel.origin_num];
                }
            }
            NSMutableArray *ball_infoArray = [NSMutableArray arrayWithCapacity:1];
            for (NSDictionary *ball_infoDic in dic[@"ball_info"]) {
                ByNetModel *model = [[ByNetModel alloc] initContentWithDic:ball_infoDic];
                model.planDic = netModel.planDic;
                [ball_infoArray addObject:model];
            }
            netModel.ball_infoArray = [ball_infoArray copy];
            
            [self.dataArray addObject:netModel];
        }
        
        
        //红人信息
        [self.redArray removeAllObjects];
        NSArray *user_red_infoAry = dictionary[@"user_red_info"];
        if ([user_red_infoAry isKindOfClass:[NSArray class]]) {
            for (NSDictionary *dic in dictionary[@"user_red_info"]) {
                ByNetModel *netModel = [[ByNetModel alloc] initContentWithDic:dic];
                [self.redArray addObject:netModel];
            }
        }
        
        
        
        [self.tableView reloadData];
        SLog(@"跟单首页 = %@", result.data);
    } failure:^(ByNetBaseResult *result) {
        
        [self.tableView.mj_header endRefreshing];
        [ByCoreToolAlert showFailureWithText:result.msg];
        [self.dataArray removeAllObjects];
        [self.tableView reloadData];
    }];

}

- (void)rightItemsAction:(NSInteger)rightIndex{
    
  
}

- (void)initViews{
    
    self.view.backgroundColor = BY_BACKGROUND_COLOR;
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor = BY_BACKGROUND_COLOR;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        if (@available(ios 11.0,*)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(0);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-49);
        } else {
            make.top.equalTo(self.view).offset(0);
            make.bottom.equalTo(self.view).offset(-49);
        }
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    

    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        ByDocumentRedsCell *cell = [ByDocumentRedsCell cellWithTableView:tableView];
        cell.dataArray = [self.redArray copy];
        cell.moreBlock = ^(){
            ByDocumentaryListVC *vc = [[ByDocumentaryListVC alloc] init];
            [self by_normalPush:vc hasNavi:YES];
        };
        
        cell.selectBlock = ^(NSInteger index){
            
            ByDocumentaryUserVC *vc = [[ByDocumentaryUserVC alloc] init];
            ByNetModel *netModel = [self.redArray objectAtIndex:index];
            vc.netModel = netModel;
            [self by_normalPush:vc hasNavi:YES];
            
        };
        return cell;
    }else{
        
        ByNetModel *netModel = [self.dataArray objectAtIndex:indexPath.row];
        ByDocumentCell *cell = [ByDocumentCell cellWithTableView:tableView];
        cell.tapViewBlock = ^() {
            ByDocumentaryUserVC *vc = [[ByDocumentaryUserVC alloc] init];
            NSLog(@"user_id = %@", netModel.user_id);
            netModel.uid = netModel.user_id;
            vc.netModel = netModel;
            [self by_normalPush:vc hasNavi:YES];
        };
        cell.betBlock = ^(){
            
            if (BY_USER && [BY_USER.uid isEqualToString:netModel.user_id]) {
                [ByCoreToolAlert showOnlyText:@"用户自己发的跟单，不能跟"];
                return ;
            }
            
            NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
            NSTimeInterval a= [dat timeIntervalSince1970];
            
            if (a < netModel.end_time.integerValue && netModel.is_result.integerValue == 0){
            
              self.netModel = [netModel copy];
              [self.handleBombView show];
                
            }else{
                
               [ByCoreToolAlert showOnlyText:@"该跟单方案已截止，无法跟单"];
            }

        };
        cell.isUser = NO;
        cell.netModel = netModel;
        return cell;
    }

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 170;
    }
    ByNetModel *netModel = [self.dataArray objectAtIndex:indexPath.row];
    
    if (netModel.public_type.integerValue == 2 || (netModel.public_type.integerValue == 1 && netModel.is_result.integerValue == 1)) {
        CGFloat height = netModel.ball_infoArray.count * 35 + 75 + 35;
        return 12 + 75 + 50 + height + 53;
    }else{
        CGFloat height =  35 + 75 + 35;
        return 12 + 75 + 50 + height + 53;
    }
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01;
    }else{
        return 76;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(5, 0, SCREEN_WIDTH - 10, 76)];
        ByDocumentarySectionView *sectionView = [[ByDocumentarySectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        sectionView.index = self.bigType;
        [header addSubview:sectionView];
        __weak typeof(self) weakSelf = self;
        sectionView.selectBlock = ^(NSInteger index){
            weakSelf.bigType = index;
            [weakSelf loadData];
        };
        sectionView.searchBlock = ^(){
            [ByCoreToolAlert showOnlyText:@"搜索"];
        };
        
        self.segTitle = [[ByCoreViewSegmentControl alloc] initWithFrame:CGRectMake(0, sectionView.bottom, SCREEN_WIDTH - 10, 36)];
        [header addSubview:self.segTitle];
        self.segTitle.sectionTitles = @[@"综合排序",@"认购金额",@"跟单金额",@"盈利率"];
        self.segTitle.backgroundColor = [UIColor whiteColor];
        self.segTitle.font = FONT(13);
        self.segTitle.scrollEnabled = YES;
        self.segTitle.textColor = [UIColor blackColor];
        self.segTitle.selectedTextColor = BY_THEME_COLOR;
        self.segTitle.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        self.segTitle.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
        self.segTitle.selectionIndicatorHeight = 3;
        self.segTitle.segmentEdgeInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.segTitle.selectedSegmentIndex = self.type - 1;
        
        [self.segTitle setIndexChangeBlock:^(NSInteger index) {
            weakSelf.type = index + 1;
            [weakSelf loadData];
        }];
        UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 35, SCREEN_WIDTH - 10, 1)];
        lbl.backgroundColor = BY_LINE_COLOR;
        [self.segTitle addSubview:lbl];
        
        return header;
        
    }else{
        return [UIView new];
    }
  
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        ByNetModel *netModel = [self.dataArray objectAtIndex:indexPath.row];
        ByDocumentaryDetailVC *vc = [[ByDocumentaryDetailVC alloc] init];
        vc.netModel = netModel;
        [self by_normalPush:vc hasNavi:YES];
    }
   
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
